namespace Daemon.Common.Helpers
{
    using System;
    using System.IO;
    using System.Net;
    using System.Net.Http;
    using System.Net.Http.Headers;
    using System.Security.Cryptography;
    using System.Text;
    using System.Web;
    using Ionic.Zip;
    public class DownloadHelper
    {
        /// <summary>
		/// Create down load response
		/// </summary>
		/// <param name="stream">Download file stream</param>
		/// <param name="fileName">Download file name</param>
		/// <param name="contentType">Content type</param>
		/// <returns>Return the file</returns>
		public static HttpResponseMessage CreateResponse(Stream stream, string fileName, string contentType)
        {
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StreamContent(stream),
            };
            response.Content.Headers.ContentLength = stream.Length;
            response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = fileName,
            };
            response.Content.Headers.Allow.Add("Range");
            response.Headers.Add("Access-Control-Expose-Headers", "Accept-Ranges, Content-Encoding, Content-Length, Content-Range");
            response.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
            return response;
        }

        // public static MemoryStream CreateZipContentResult(ZipFile zipFile)
        // {
        //     var memoryStream = new MemoryStream();
        //     zipFile.Save(memoryStream);
        //     // // Reset the MemoryStream position to the beginning
        //     // memoryStream.Position = 0;
        //     return memoryStream;
        // }

        public static HttpResponseMessage CreateCustomContentResult(MemoryStream stream, string fileName, string contentType)
        {
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);

            response.Content = new StreamContent(stream);
            response.Content.Headers.ContentDisposition =
                new ContentDispositionHeaderValue("attachment") { FileName = fileName };
            response.Content.Headers.Add("Access-control-Expose-Headers", "Content-Disposition"); // add Access-control-Expose-Headers to allow client getting Content-Disposition header to solve CORS issue.
            response.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);

            return response;
        }

        /// <summary>
        /// Save the object in cache for 30 seconds. Users must redeem the one time key within 30 seconds.
        /// </summary>
        /// <returns>One time use key</returns>
        // public static string GetOneTimeDownloadKey(object cacheData)
        // {
        //     string hashKey = GetDateTimeHash();

        //     // Decrease size of hash so it looks better in client URL (PM Requirement)
        //     hashKey = hashKey.Substring(0, 16);
        //     HttpRuntime.Cache.Insert(hashKey, cacheData, null, Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(30));
        //     return hashKey;
        // }

        // /// <summary>
        // /// Get the document id from the cache, then remove it.
        // /// </summary>
        // /// <param name="hashKey">Key for the hash</param>
        // /// <returns>Return One time use key</returns>
        // public static object RedeemOneTimeDownloadKey(string hashKey)
        // {
        //     object cacheData = HttpRuntime.Cache.Get(hashKey);
        //     if (cacheData == null)
        //     {
        //         throw new PreconditionFailedException("The document you requested to view has expired. Please try again.");
        //     }

        //     HttpRuntime.Cache.Remove(hashKey);
        //     return cacheData;
        // }

        private static string GetDateTimeHash()
        {
            using (MD5 md5Hash = MD5.Create())
            {
                byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(DateTime.Now.ToFileTime().ToString() + Guid.NewGuid().ToString()));
                StringBuilder builder = new StringBuilder();
                for (int i = 0; i < data.Length; i++)
                {
                    builder.Append(data[i].ToString("x2"));
                }

                return builder.ToString();
            }
        }
    }
}
